<template>
  <div id="app" style="z-index: 10;">
    <img src="../../../../public/images/index/dongman04.jpg" style="width: 1200px;position: relative;top: 4px">
    <!--1578 1987-->
    <el-col :span="8" style="margin: 0 auto;">
      <!--卡片功能-->
      <el-tabs type="border-card" shadow="hover"
               style="width: 824px;height: 463px;position: fixed;top: 50%;left: 50%;margin-left: -412px;margin-top: -211px;border-radius: 20px">
        <!--关闭功能-->
        <i class="el-icon-close" style="overflow: hidden;position: relative;left: 750px;font-size: 30px"
           @click="$router.push('/')"></i>

        <div style="overflow: hidden;position: relative;bottom: 20px;">
          <!--扫码功能-->
          <div style="position: relative;left: 100px;top: 30px;font-size: 25px;overflow: hidden">扫码登录</div>
          <div id="c1"></div>
          <!--用户名和密码登录注册功能-->
          <div id="c2">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleFrom"
                     style="width: 400px; margin: 50px auto;margin-right: 50px" label-width="70px">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm.username" placeholder="请输入用户名"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button style="border-radius: 12px; position: relative;right: -50px" type="primary"
                           @click="loginList('ruleForm')">登录
                </el-button>

                <el-button style="border-radius: 12px; position: relative;right: -100px;" type="primary"
                           @click="$router.push('/sys-user/product/reg')">注册
                </el-button>
                <!--qq微信手机图片-->
                <a href="" style="position: relative;top: 95px;left: 60px"><img src="../imgs/phonelogo-2.png"
                                                                                style="width: 35px"></a>
                <a href="" style="position: relative;top: 95px;left: -72px"><img src="../imgs/weixinlogo-2.png"
                                                                                 style="width: 35px"></a>
                <a href="" style="position: relative;top: 95px;left: -210px"><img src="../imgs/qqlogo-1.png"
                                                                                  style="width: 35px"></a>
              </el-form-item>
              <!--qq微信手机登录-->
              <a href="" style="color: dodgerblue;position: relative;top: 30px;left: 10px">登录</a>
              <a href="" style="color: dodgerblue;position: relative;top: 30px;left: 80px">登录</a>
              <a href="" style="color: dodgerblue;position: relative;top: 30px;left: 150px">登录</a>
            </el-form>
          </div>
          <div style="width: 200px;position: relative;bottom: -80px;left: 70px;font-size: 14px">请使用御兽阁客户端扫码<br>登录或扫码下载App登录
          </div>
          <!--二维码功能-->
<!--          <img src="../imgs/erweimalogo-2.png" style="width: 200px;position: relative;bottom: 188px;left: -22px">-->
          <div id="qrcode"  style="width: 200px;position: relative;bottom: 188px;left:50px">
            <vue-qr ref="qr" :text="qrText" :size="200"></vue-qr>
          </div>
          <div style="text-align:right;">
            <a-button type="primary" @click="saveCode(qrId)">保存到本地</a-button>
          </div>
        </div>
      </el-tabs>
    </el-col>
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      // imageUrl: require('@/assets/tianyuan.png'),
      qrText: '八仙过海显神通,\n' +
          '项目峰会入囊中!',
      qrId:'',
      ruleForm: {
        username: '王芳',
        password: '123456'
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ]
      },
      userId: ''
    }
  },
  methods: {
    saveCode(data) {
      const fileName = data + 'png'
      let img = document.getElementById('qrcode').getElementsByTagName('img')[0].src

      let aLink = document.createElement('a')
      let blob = this.base64ToBlob(img)
      let evt = document.createEvent('HTMLEvents')
      evt.initEvent('click', true, true) // initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = fileName
      aLink.href = URL.createObjectURL(blob)
      // aLink.dispatchEvent(evt);
      aLink.click()
    },
    //base64转blob
    base64ToBlob(code) {
      let parts = code.split(';base64,')
      let contentType = parts[0].split(':')[1]
      let raw = window.atob(parts[1])
      let rawLength = raw.length
      let uInt8Array = new Uint8Array(rawLength)
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: contentType })
    },
    // 提交表单
    loginList(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              let url = 'http://localhost:17701/user/login';
              console.log('url = ' + url);

              let formData = this.qs.stringify(this.ruleForm);
              console.log('formData = ' + formData);

              this.axios.post(url, formData).then((response) => {
                let jsonResult = response.data;
                if (jsonResult.state == 20000) {
                  this.$message({
                    message: '登录成功！',
                    type: 'success',
                    duration: 2000 // 持续显示弹窗的时间，单位为毫秒，默认为3000
                  });
                  let jwt = jsonResult.data;
                  this.userId = jsonResult.data.id;
                  //将userId保存到本地
                  localStorage.setItem('userId',this.userId);
                  let jwtJsonString = JSON.stringify(jwt)
                  localStorage.setItem('localJwt', jwtJsonString);
                  console.log('已经将登录信息存入到localStorage中，即将跳转页面……');
                  this.addUserCart()
                  this.loadCartByUser();
                  this.$router.push('/');
                } else {
                  this.$alert(jsonResult.message, '错误', {
                    confirmButtonText: '确定',
                    callback: action => {
                    }
                  });
                }
              });
            } else {
              console.log('error submit!!');
              return false;
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    addUserCart() {
      let url = 'http://localhost:14001/shopping-cart/add-new?userId=' + this.userId;

      console.log('url = ' + url);

      let localJwt = JSON.parse(localStorage.getItem('localJwt'));

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt.token
            }
          })
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '新增购物车成功！',
            type: 'success',
            duration: 2000, // 持续显示弹窗的时间，单位为毫秒，默认为3000
          });
        }
      });
    },

    loadCartByUser() {
      let url = 'http://localhost:14001/shopping-cart/standardByUser?userId=' + this.userId;
      console.log('url = ' + url);

      let localJwt = JSON.parse(localStorage.getItem('localJwt'));

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt.token
            }
          }).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state = 20000) {
          let cart = jsonResult.data;
          let cartJsonString = JSON.stringify(cart)
          localStorage.setItem("cart", cartJsonString)
          console.log("将购物车信息存入localStorage成功!")
        }
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    }

  }
}
</script>

<style>
#c1 {
  width: 200px;
  height: 200px;
  background-color: green;
  position: relative;
  top: 50px;
  left: 50px;
  float: left;
}

#c2 {
  float: right;

}

#c3 {
  position: relative;
  top: -60px;
  left: -80px;
}
</style>